package com.store.app.adapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.R;
import com.store.app.activity.ConfirmPaymentActivityForLLM;
import com.store.app.activity.WebViewTGActivity;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.FreeBean;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.OpenTaoBaoApp;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;

public class OrderFreeAdapter extends BaseAdapter implements IOnHttpListener {
    private List<FreeBean> goodsList;
    private Context context;
    private Dialog dialog;
    private ListView mListView;

    public void updateProgressPartly(long diftime) {
        try {
            int firstVisiblePosition = mListView.getFirstVisiblePosition() - 1;
            int lastVisiblePosition = mListView.getLastVisiblePosition();
            for (int i = firstVisiblePosition; i < lastVisiblePosition; i++) {
                View view = mListView.getChildAt(i - firstVisiblePosition);
                if (view == null) {
                    return;
                }
                View time = view.findViewById(R.id.down_time_layout);
                if (time != null && time.isShown()) {
                    goToRefreshView(time, i, diftime);
                }
            }
        } catch (Exception e) {
        }
    }

    public OrderFreeAdapter(List<FreeBean> goodsList, Context context, ListView mListView) {
        this.goodsList = goodsList;
        this.context = context;
        this.mListView = mListView;
    }

    @Override
    public int getCount() {
        return goodsList.size();
    }

    @Override
    public Object getItem(int position) {
        return goodsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_free, null);

//            viewHolder.title = (TextView) convertView.findViewById(R.id.order_title);
//            viewHolder.numqry = (TextView) convertView.findViewById(R.id.order_numqry);
//            convertView.findViewById(R.id.order_name).setVisibility(View.GONE);
//            convertView.findViewById(R.id.order_phone).setVisibility(View.GONE);
//            viewHolder.date = (TextView) convertView.findViewById(R.id.order_date);
//            viewHolder.num = (TextView) convertView.findViewById(R.id.order_num);
//            viewHolder.price = (TextView) convertView.findViewById(R.id.order_price);
//            viewHolder.check = (TextView) convertView.findViewById(R.id.order_check);
//            viewHolder.id = (TextView) convertView.findViewById(R.id.order_id);
//            viewHolder.btn_check = (TextView) convertView.findViewById(R.id.order_btn_check);
//            viewHolder.btn_cancle = (TextView) convertView.findViewById(R.id.order_btn_cancle);
//            convertView.findViewById(R.id.order_take_phone).setVisibility(View.GONE);
//            viewHolder.title_coin = (ImageView) convertView.findViewById(R.id.order_title_coin);
//            viewHolder.price_coin = (ImageView) convertView.findViewById(R.id.order_price_coin);
//            viewHolder.logistics = (TextView) convertView.findViewById(R.id.order_logistics);
//            viewHolder.tv_logistics = (TextView) convertView.findViewById(R.id.order_btn_logistics);
////            viewHolder.tvPayWay = (TextView) convertView.findViewById(R.id.order_pay_way);
//            viewHolder.external_order_no = (TextView) convertView.findViewById(R.id.external_order_no);
//            viewHolder.down_time_layout = convertView.findViewById(R.id.down_time_layout);
//            viewHolder.order_remark = (TextView) convertView.findViewById(R.id.order_remark);

            viewHolder.order_img = (ImageView) convertView.findViewById(R.id.order_img);
            viewHolder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            viewHolder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
            viewHolder.tv_price_return = (TextView) convertView.findViewById(R.id.tv_price_return);
            viewHolder.tv_status = (TextView) convertView.findViewById(R.id.tv_status);
            viewHolder.tv_order_no = (TextView) convertView.findViewById(R.id.tv_order_no);
            viewHolder.tv_date = (TextView) convertView.findViewById(R.id.tv_date);
            viewHolder.tv_external_order_no = (TextView) convertView.findViewById(R.id.tv_external_order_no);
            viewHolder.tv_order_remark = (TextView) convertView.findViewById(R.id.tv_order_remark);
            viewHolder.order_btn_cancle = (TextView) convertView.findViewById(R.id.order_btn_cancle);
            viewHolder.order_customer = (TextView) convertView.findViewById(R.id.order_customer);
            viewHolder.order_btn_logistics = (TextView) convertView.findViewById(R.id.order_btn_logistics);
            viewHolder.oyb_min = (TextView) convertView.findViewById(R.id.oyb_min);
            viewHolder.oyb_sec = (TextView) convertView.findViewById(R.id.oyb_sec);
            viewHolder.down_time_layout = (RelativeLayout) convertView.findViewById(R.id.down_time_layout);
            viewHolder.ll_external_order_no = (LinearLayout) convertView.findViewById(R.id.ll_external_order_no);
            viewHolder.ll_remark = (LinearLayout) convertView.findViewById(R.id.ll_remark);
            viewHolder.ll_date = (LinearLayout) convertView.findViewById(R.id.ll_date);
            viewHolder.rl_bottom_btn = (RelativeLayout) convertView.findViewById(R.id.rl_bottom_btn);
            viewHolder.ll_tip = (LinearLayout) convertView.findViewById(R.id.ll_tip);
            viewHolder.ll_order_btn_check = (LinearLayout) convertView.findViewById(R.id.ll_order_btn_check);
            viewHolder.ll_return_time = (LinearLayout) convertView.findViewById(R.id.ll_return_time);
            viewHolder.ll_contact = (LinearLayout) convertView.findViewById(R.id.ll_contact);
            viewHolder.ll_address = (LinearLayout) convertView.findViewById(R.id.ll_address);
            viewHolder.tv_return_time = (TextView) convertView.findViewById(R.id.tv_return_time);
            viewHolder.tv_contact = (TextView) convertView.findViewById(R.id.tv_contact);
            viewHolder.tv_contact_tel = (TextView) convertView.findViewById(R.id.tv_contact_tel);
            viewHolder.tv_address = (TextView) convertView.findViewById(R.id.tv_address);


            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.ll_return_time.setVisibility(View.GONE);

        viewHolder.order_customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String chatid = "diandongzhushouserviceagent";
                String title  ="官方客服";
                Intent intent = new Intent(context, ChatActivity.class);
                intent.putExtra("userId", chatid);
                intent.putExtra("groupName", title);
                context.startActivity(intent);
            }
        });
        //如果有联系人就显示
        if(!TextUtils.isEmpty(goodsList.get(position).getContact_person())){
            viewHolder.tv_contact.setText(goodsList.get(position).getContact_person());
        }else{
            viewHolder.tv_contact.setText("");
        }
        //有电话就显示
        if(!TextUtils.isEmpty(goodsList.get(position).getContact_tel())){
            viewHolder.tv_contact_tel.setText(goodsList.get(position).getContact_tel());
        }else{
            viewHolder.tv_contact_tel.setText("");
        }
        //有收货地址就显示
        if(!TextUtils.isEmpty(goodsList.get(position).getDelivery_address())){
            viewHolder.ll_address.setVisibility(View.VISIBLE);
            viewHolder.tv_address.setText(goodsList.get(position).getDelivery_address());
        }else{
            viewHolder.ll_address.setVisibility(View.GONE);
            viewHolder.tv_address.setText("");
        }

        //如果有外部订单号则显示
        if (!TextUtils.isEmpty(goodsList.get(position).getExternal_order_no())) {
            viewHolder.ll_external_order_no.setVisibility(View.VISIBLE);
            viewHolder.tv_external_order_no.setText(goodsList.get(position).getExternal_order_no());
        } else {
            viewHolder.ll_external_order_no.setVisibility(View.GONE);
        }
        //如果有备注则显示
        if (!TextUtils.isEmpty(goodsList.get(position).getRemark())) {
            viewHolder.ll_remark.setVisibility(View.VISIBLE);
            viewHolder.tv_order_remark.setText(goodsList.get(position).getRemark());
        } else {
            viewHolder.ll_remark.setVisibility(View.GONE);
        }
        String img = goodsList.get(position).getGoods_pic_info_url();
        ImageLoader.getInstance().displayImage(img, viewHolder.order_img, options);
        //商品名
        String title = goodsList.get(position).getItem_goods_title();
        if (!TextUtils.isEmpty(title)) {
            viewHolder.tv_title.setText(title);
        }
        //商品单价
        String discount_price = goodsList.get(position).getSale_fee();

        if (!TextUtils.isEmpty(discount_price)) {
            viewHolder.tv_price.setText(discount_price);
        }
        //时间
        String order_date = goodsList.get(position).getOrder_date();
        if (!TextUtils.isEmpty(order_date)) {
            viewHolder.ll_date.setVisibility(View.VISIBLE);
            viewHolder.tv_date.setText(order_date);
        } else {
            viewHolder.ll_date.setVisibility(View.GONE);
        }
        //数量
//        String item_qty = goodsList.get(position).getItem_qty();
        //商品价格
        String item_sale_price = goodsList.get(position).getTotal_fee();
        if (!TextUtils.isEmpty(item_sale_price)) {
            viewHolder.tv_price_return.setText(item_sale_price);
        }
        //状态
        String status = goodsList.get(position).getStatus();
        viewHolder.ll_tip.setVisibility(View.GONE);
        viewHolder.rl_bottom_btn.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(status)) {
            if (status.equals("processing")) {

                viewHolder.tv_status.setText("已预定");
                viewHolder.ll_tip.setVisibility(View.VISIBLE);
                //如果是自营的要隐藏确认订单
                if (goodsList.get(position).getOrder_type().equals(SettingData.DATA_SOURCE_MTH)) {
                    viewHolder.ll_order_btn_check.setVisibility((View.GONE));
                } else {
                    viewHolder.ll_order_btn_check.setVisibility((View.VISIBLE));
                }
                viewHolder.down_time_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.v("zyl", "goodsList.get(position).getOrder_type():" + goodsList.get(position).getOrder_type());
                        if (goodsList.get(position).getOrder_type().equals(SettingData.DATA_SOURCE_TAOBAO)) {
                            creatDialog(goodsList.get(position).product_source);
                        } else if (goodsList.get(position).getOrder_type().equals(SettingData.DATA_SOURCE_MTH)) {
                            if (MoneyUtil.moneyBigThan(goodsList.get(position).getSale_fee(), "0")) {
                                Intent intent = new Intent(context, ConfirmPaymentActivityForLLM.class);
                                intent.putExtra("num", 1);
                                intent.putExtra("money", goodsList.get(position).getSale_fee());
                                intent.putExtra("bean", goodsList.get(position));
                                context.startActivity(intent);
                            } else {
                                ToastUtils.showTextToast(context, "商品价格需大于0");
                            }
                        }

                    }
                });
                viewHolder.order_customer.setVisibility(View.GONE);
                viewHolder.order_btn_logistics.setVisibility(View.GONE);
                viewHolder.order_btn_cancle.setVisibility((View.VISIBLE));
                viewHolder.order_btn_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancleDialog(goodsList.get(position).getOrder_id());
                    }
                });
            } else if (status.equals("closed")) {
                viewHolder.order_customer.setVisibility(View.GONE);
                viewHolder.ll_order_btn_check.setVisibility((View.GONE));
                viewHolder.order_btn_cancle.setVisibility((View.GONE));
                viewHolder.tv_status.setText("已返款");
                //物流信息
                try {
                    String s_logistics = goodsList.get(position).getLogistics();
                    JSONObject log_obj = new JSONObject(s_logistics);
                    String s_company = log_obj.getString("company");
                    String s_number = log_obj.getString("number");
                    if (!TextUtils.isEmpty(s_company) && !TextUtils.isEmpty(s_number)) {
                        viewHolder.order_btn_logistics.setVisibility(View.VISIBLE);
                    } else {
                        viewHolder.order_btn_logistics.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    viewHolder.order_btn_logistics.setVisibility(View.GONE);
                }
                viewHolder.order_btn_logistics.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent6 = new Intent();
                        intent6.setClass(context, WebViewTGActivity.class);
                        intent6.putExtra("title", "查看物流");
                        intent6.putExtra("url", SettingData.http + "/openapi/h5/c/payback/logistics?order_id=" + goodsList.get(position).getOrder_id());
                        context.startActivity(intent6);
                    }
                });

            } else if (status.equals("confirmed")) {
                viewHolder.ll_return_time.setVisibility(View.VISIBLE);

                viewHolder.ll_order_btn_check.setVisibility((View.GONE));
                viewHolder.order_btn_cancle.setVisibility((View.GONE));
                viewHolder.order_btn_logistics.setVisibility(View.GONE);
                viewHolder.tv_status.setText("已下单");
                String s_date=getTheDistanceToNow(order_date);
                if("timeout".equals(s_date)){
                    viewHolder.rl_bottom_btn.setVisibility(View.VISIBLE);
                    viewHolder.order_customer.setVisibility(View.VISIBLE);
                    viewHolder.tv_return_time.setText("返款异常，请点击下方按钮联系客服");
                }else {
                    viewHolder.rl_bottom_btn.setVisibility(View.GONE);
                    viewHolder.order_customer.setVisibility(View.GONE);
                    viewHolder.tv_return_time.setText("差额部分将于"+s_date+"之前返还到您的账户");
                }
            } else if (status.equals("cancelled")) {
                viewHolder.rl_bottom_btn.setVisibility(View.GONE);
                viewHolder.order_customer.setVisibility(View.GONE);
                viewHolder.ll_order_btn_check.setVisibility((View.GONE));
                viewHolder.order_btn_cancle.setVisibility((View.GONE));
                viewHolder.order_btn_logistics.setVisibility(View.GONE);
                viewHolder.tv_status.setText("已取消");
            }
        }
        viewHolder.ll_order_btn_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.pop_taobao_order_confirm, null);
                final EditText editText1 = (EditText) linearLayout.findViewById(R.id.et_input_taobao_order);
                TextView tvCancel = (TextView) linearLayout.findViewById(R.id.cancel);
                TextView tvSubimt = (TextView) linearLayout.findViewById(R.id.submit);

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setView(linearLayout);

                dialog = builder.show();
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                tvSubimt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(editText1.getText().toString().trim())) {
                            ToastUtils.showTextToast(context, "请输入淘宝订单号");
                        } else if (editText1.getText().toString().trim().length() < 16) {
                            ToastUtils.showTextToast(context, "请填写正确的淘宝订单号！");
                        } else {
                            NetRequest netRequest = new NetRequest(OrderFreeAdapter.this, context);
                            netRequest.requestOrderConfirm(3, goodsList.get(position).getOrder_id(), editText1.getText().toString().trim());
                        }
                    }
                });
            }
        });
        //订单号
        String order_no = goodsList.get(position).getOrder_no();
        if (!TextUtils.isEmpty(order_no)) {
            viewHolder.tv_order_no.setText(order_no);
        }
        goToRefreshView(viewHolder.down_time_layout, position, 0);  //刷新时间
        return convertView;
    }

    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //确认订单成功，跳转到待返款页面
        if (requestId == 3) {
            if (dialog != null) {
                dialog.dismiss();
            }
            EventBus.getDefault().post(new EventBusBean(227));
        }
        //取消订单成功，刷新列表数据
        else if (requestId == 4) {
            if (dialog != null) {
                dialog.dismiss();
            }
            EventBus.getDefault().post(new EventBusBean(228));
        }
    }

    private Dialog alterDialog;
    public static String getTheDistanceToNow(String s_date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = simpleDateFormat.parse(s_date);
            long l_gettime = date.getTime();
            long nowtime=new Date().getTime();

            long distance=(nowtime-l_gettime)/1000;
            if(distance>=172800){
                //超过48小时
                return "timeout";
            }else{
                //不超过48小时
                long outtime= l_gettime+172800000;
                Date o_date = new Date(outtime);
                String s_outdate = simpleDateFormat.format(o_date);
                return s_outdate;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return "timeout";
    }

    private void creatDialog(final String product_source) {
        if (product_source != null) {
            OpenTaoBaoApp.open(context.getApplicationContext(), product_source);
        } else {
            Toast.makeText(context, "淘口令缺失", Toast.LENGTH_SHORT).show();
        }
//        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.goto_pay_tips, null);
//        TextView tvCancel = (TextView) linearLayout.findViewById(R.id.cancel);
//        ((TextView) linearLayout.findViewById(R.id.order_tips)).setText(Html.fromHtml(context.getString(R.string.goto_pay)));
//        TextView tvSubimt = (TextView) linearLayout.findViewById(R.id.submit);
////        linearLayout.findViewById(R.id.et_input_taobao_order).setVisibility(View.GONE);
//
//        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
//        builder.setView(linearLayout);
//
//        alterDialog = builder.show();
//        tvCancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                alterDialog.dismiss();
//            }
//        });
//        tvSubimt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (product_source != null) {
//                    OpenTaoBaoApp.open(context.getApplicationContext(), product_source);
//                } else {
//                    Toast.makeText(context, "淘口令缺失", Toast.LENGTH_SHORT).show();
//                }
//                alterDialog.dismiss();
//            }
//        });
    }

    EditText editText;

    private void cancleDialog(final String orderid) {
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.goto_cancle_order, null);
        TextView tvCancel = (TextView) linearLayout.findViewById(R.id.cancel);
        TextView tvSubimt = (TextView) linearLayout.findViewById(R.id.submit);
        editText = (EditText) linearLayout.findViewById(R.id.order_remark);
//        linearLayout.findViewById(R.id.et_input_taobao_order).setVisibility(View.GONE);

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
        builder.setView(linearLayout);

        alterDialog = builder.show();
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alterDialog.dismiss();
            }
        });
        tvSubimt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editText.getText().toString())) {
                    Toast.makeText(context, "请输入取消理由", Toast.LENGTH_SHORT).show();
                    return;
                }

                NetRequest netRequest = new NetRequest(OrderFreeAdapter.this, context);
                netRequest.requestOrderCancle(4, orderid, editText.getText().toString().trim());

                alterDialog.dismiss();
            }
        });

        editText.setLongClickable(false);

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastUtils.showTextToast(context, msg);
    }

    private void goToRefreshView(View time, int position, long diftime) {
        TextView minTv = (TextView) time.findViewById(R.id.oyb_min);
        TextView secTv = (TextView) time.findViewById(R.id.oyb_sec);
        if (diftime == 0) {
            return;
        }
        long difftime = Long.valueOf(goodsList.get(position).diff_time) / 1000 - diftime;
        if (difftime <= 0) {
            minTv.setText("00");
            secTv.setText("00");
        } else {
            long min = ((difftime / (60)));
            long s = (difftime - min * 60);
            String s_min = min + "";
            if (s_min.length() == 1) {
                s_min = "0" + s_min;
            }
            String s_s = s + "";
            if (s_s.length() == 1) {
                s_s = "0" + s_s;
            }
            minTv.setText(s_min);
            secTv.setText(s_s);
        }
    }


    class ViewHolder {
//        private ImageView img;
//        private TextView title;
//        private TextView numqry;
//        private TextView date;
//        private TextView num;
//        private TextView price;
//        private TextView check;
//        private TextView id;
//        private TextView btn_check;
//        private TextView btn_cancle;
//        private View down_time_layout;
//        private TextView logistics;
//        private ImageView title_coin;
//        private ImageView price_coin;
//        //        private TextView tvPayWay;
//        private TextView external_order_no;
//        private TextView order_remark;
//        private TextView tv_logistics;


        private ImageView order_img;            //订单图片
        private TextView tv_title;              //商品标题
        private TextView tv_price;              //商品价格
        private TextView tv_price_return;       //返现价格
        private TextView tv_status;             //订单状态
        private TextView tv_order_no;           //订单编号
        private TextView tv_date;               //订单时间
        private TextView tv_external_order_no;  //关联订单
        private TextView tv_order_remark;        //备注
        private TextView order_btn_cancle;       //取消订单
        private TextView order_customer;        //联系客服
        private TextView order_btn_logistics;    //查看物流
        private RelativeLayout down_time_layout; //倒计时布局
        private TextView oyb_min;               //分钟
        private TextView oyb_sec;               //秒数
        private LinearLayout ll_external_order_no;
        private LinearLayout ll_remark;
        private LinearLayout ll_date;
        private RelativeLayout rl_bottom_btn;
        private LinearLayout ll_tip;
        private LinearLayout ll_order_btn_check;
        private LinearLayout ll_return_time;
        private LinearLayout ll_contact;
        private LinearLayout ll_address;
        private TextView tv_contact;
        private TextView tv_address;
        private TextView tv_contact_tel;
        private TextView tv_return_time;


    }

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.default_picture_s)
            .showImageOnFail(R.drawable.default_picture_s)
            .showStubImage(R.drawable.default_picture_s)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
}
